import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { Permission, useUserStore } from "@/stores/userStore";
import NotPermission from "@/pages/403";
interface AuthRouteProps {
  children: React.ReactNode;
}

const AuthRoute: React.FC<AuthRouteProps> = ({ children }) => {
  const { token, permissions } = useUserStore();
  const location = useLocation();

  // 如果没有token，重定向到登录页
  if (!token) {
    // 将当前路径保存到state中，登录后可以跳转回来
    return <Navigate to="/login" state={{ from: location.pathname }} replace />;
  }

  const hasPermissionFn = (arr: Permission[], path: string): boolean => {
    return arr.some((item) => {
      if (item.children) {
        return hasPermissionFn(item.children, path);
      }
      return item.ps_api_path === path;
    });
  };

  // 检查用户是否有权限访问当前路径
  const hasPermission = hasPermissionFn(permissions, location.pathname);

  // 如果没有权限，重定向到403页面
  if (!hasPermission) {
    return <NotPermission />;
  }

  return <>{children}</>;
};

export default AuthRoute;
